
function isNumeric( input ) {
    return /^\d+$/.test(input);
}

var fs = require('fs');

var Router = {
    
    setControllersDir: function( absolutePath ) {
        this.controllersDir = absolutePath;
    },
    to: function( URI, req, res ) {

        if( !this.toController( URI, req, res ) )
            if( !this.toController( '/_extra_/_404', req, res ) ) {
                res.writeHead( 404 );
                res.end();
            }
            
    },
    toController: function( URI, req, res ) {

        var dirs = URI.split('/');

        var basePath = this.controllersDir;


        while( dirs.length>0 ) {

            var thisDir = dirs.shift();

            if( !thisDir )
                continue;

            var controllerFound = this.findControllerFile( basePath, thisDir );

            if( controllerFound ) {
                
                return callControllerFn( controllerFound, req, res, dirs );
                
            }

            if( isNumeric(thisDir) && fs.existsSync( basePath + '/_numeric' ) )
                thisDir = '_numeric';
            else if( !fs.existsSync( basePath + '/' + thisDir ) && fs.existsSync( basePath + '/_default' ) )
                thisDir = '_default';

            basePath += '/'+thisDir;

        }

        function callControllerFn( controller, req, res, argsArray ) {

            var fnName,
                methodPostFix = '_'+req.method,
                searchList = [];


            if( fnName = argsArray.shift() ) {
                searchList.push( fnName + methodPostFix, fnName );
            }

            if( isNumeric(fnName) ) {
                searchList.push( '_numeric'+methodPostFix, '_numeric' );
            }

            searchList.push( '_default'+methodPostFix, '_default' );


            for( var i in searchList ) {

                var fnNameItem = searchList[i];

                if( controller[fnNameItem] ) {
                    fnName = fnNameItem;
                    break;
                }

            }

            if( !fnName )
                return false;

            controller[fnName].call( controller, req, res, argsArray );

            return true;

        }
    },
    findControllerFile: function( path, name ) {

        var ctrlerFile = false;

        if( !(ctrlerFile = loadFile( path+'/'+name+'.js' )) ) {
            
            if( !(ctrlerFile = loadFile( path+'/_numeric.js' )) && /^\d+$/.test(name) )
                ctrlerFile = loadFile( path+'/_default.js' );

        }

        return ctrlerFile;


        function loadFile( path ) {
            var loaded;
            try {
                loaded = require(path);
            }
            catch (e) {
                loaded = false;
            }
            return loaded;
        }

    }

};

module.exports = Router;